import logging
import logging.handlers
import os
import sys
from datetime import datetime
from app.core.config.settings import settings


def setup_logging():
    """设置日志配置"""

    # 创建日志目录
    log_dir = os.path.join(os.path.dirname(__file__), "../../../logs")
    os.makedirs(log_dir, exist_ok=True)

    # 配置日志格式
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )

    # 设置根日志级别
    root_logger = logging.getLogger()
    root_logger.setLevel(getattr(logging, settings.log_level.upper()))

    # 控制台处理器
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setFormatter(formatter)
    root_logger.addHandler(console_handler)

    # 文件处理器（按大小轮转）
    if settings.log_file:
        file_handler = logging.handlers.RotatingFileHandler(
            filename=os.path.join(log_dir, settings.log_file),
            maxBytes=settings.log_max_size,
            backupCount=settings.log_backup_count,
            encoding='utf-8'
        )
        file_handler.setFormatter(formatter)
        root_logger.addHandler(file_handler)

    # 错误日志文件
    error_handler = logging.handlers.RotatingFileHandler(
        filename=os.path.join(log_dir, "error.log"),
        maxBytes=settings.log_max_size,
        backupCount=settings.log_backup_count,
        encoding='utf-8'
    )
    error_handler.setLevel(logging.ERROR)
    error_handler.setFormatter(formatter)
    root_logger.addHandler(error_handler)

    # 设置第三方库的日志级别
    logging.getLogger("uvicorn").setLevel(logging.WARNING)
    logging.getLogger("sqlalchemy").setLevel(logging.WARNING)
    logging.getLogger("httpx").setLevel(logging.WARNING)


class ContextFilter(logging.Filter):
    """添加上下文信息的日志过滤器"""

    def filter(self, record):
        record.service_name = settings.app_name
        record.service_version = settings.app_version
        return True


# 添加上下文过滤器
logging.getLogger().addFilter(ContextFilter())